<template>
  <!-- 头部组件 -->
  <navbar class="header">
    <template #rightContent>
      <!-- 右侧插槽内容 -->
      <text>浏览历史</text>
    </template>
  </navbar>
  <!-- search -->
  <view class="search">
    <u-search v-model="searchKey" :clearabled="false" @search="handleSearch" placeholder="关键字搜索" :showAction="false"
      shape="square" margin="0 30rpx 26rpx 30rpx" height="80rpx" bg-color="#f7f7f7"
      placeholderColor="#9ca3af"></u-search>
  </view>
  <!-- contain -->
  <view class="history">
    <view class="historyContain" v-for="(group, groupIndex) of filteredGroupInfo" :key="groupIndex"
      v-if="filteredGroupInfo.length > 0">
      <!-- 时间 -->
      <view class="date">
        <image class="icon" src="@/static/日期节点ico.png"></image>
        <view class="text">{{ group.date }}</view>
      </view>
      <!-- 信息 -->
      <view class="information">
        <view class="contain" v-for="(item, itemIndex) of group.list" :key="item.conversaionId" @click="getTalk(item)">
          <view class="title">
            <text>
              {{ item.conversationTitle}}
            </text>
            <image class="titleIcon" src="@/static/最新政策详情ico.png"></image>
          </view>
          <view class="time">
            <image class="timeIcon" src="@/static/最新政策时间ico.png"></image>
            <text>{{item.createdTime}}</text>
          </view>
          <view class="detail">
            <text>{{ item.syscontent }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import navbar from '@/components/navbar/navbar.vue'
  import {
    onLoad,
    onReachBottom
  } from '@dcloudio/uni-app'
  import {
    ref
  } from 'vue'
  import {
    history
  } from '@/api/person.js'
  // 筛选后的数据：用于页面渲染
  const filteredList = ref([]);
  // 分组后的筛选数据：按日期分组
  const filteredGroupInfo = ref([]);

  const pageNum = ref(1);
  const pageSize = ref(10);
  const loading = ref(false);
  const noMore = ref(false);
  const isSearching = ref(false);

  const searchKey = ref('');

  onLoad(() => {
    loadData()
  })

  const loadData = () => {
    if (loading.value || noMore.value) return;
    loading.value = true;
    history({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      syscontent: isSearching.value ? searchKey.value.trim() : ''
    }).then((res) => {
      console.log(res)
      if (res.code === 200) {
        const newData = res.rows || [];
        if (pageNum.value === 1 && newData.length === 0) {
          uni.showToast({
            title: '没有发现您的历史记录',
            icon: 'none',
            duration: 2000
          });
          loading.value = false;
          return;
        }
        const filteredNewData = newData.filter(item =>
          !filteredList.value.some(old => old.conversationId === item.conversationId)
        );
        filteredList.value = [...filteredList.value, ...filteredNewData];
        groupByDate(filteredList.value);
        if (newData.length < pageSize.value) {
          noMore.value = true;
        }
        if (isSearching.value && newData.length === 0) {
          uni.showToast({
            title: '没有找到相关结果',
            icon: 'none',
            duration: 2000
          });
        }
      }
      loading.value = false;
    })
  }

  onReachBottom(() => {
    if (loading.value || noMore.value) return;
    pageNum.value++;
    loadData();
  });

  const handleSearch = () => {
    const key = searchKey.value.trim();
    isSearching.value = !!key;
    pageNum.value = 1;
    noMore.value = false;
    filteredList.value = [];
    loadData();
  };

  const groupByDate = (data) => {
    const groupMap = {};
    data.forEach(item => {
      const date = formatDate(item.createdTime);
      if (!groupMap[date]) {
        groupMap[date] = {
          date,
          list: []
        };
      }
      groupMap[date].list.push(item);
    });
    // 按日期倒序排列（最新的在前）
    filteredGroupInfo.value = Object.values(groupMap).sort((a, b) =>
      new Date(b.date.replace(/年|月|日/g, '-')) - new Date(a.date.replace(/年|月|日/g, '-'))
    );
  };

  const formatDate = (timeStr) => {
    if (!timeStr) return '';
    const datePart = timeStr.split(' ')[0];
    return datePart.replace(/-/g, '年') + '日';
  };

  //TODO 获取历史详情
  const getTalk = (item) => {
    uni.navigateTo({
      url: '/pages/newPolicy/newPolicy'
    })
  }
</script>

<style lang="scss">
  .header {
    color: #fff;
    font-size: 36rpx;
  }

  :deep(.right-content) {
    margin-right: 75rpx;
  }

  .search {
    margin-top: 30rpx;
    width: 100%;
    height: 106rpx;
  }

  .history {
    margin: 30rpx 30rpx 0 30rpx;
    height: 100vh;

    .historyContain {
      .date {
        display: flex;
        align-items: center;
        gap: 16rpx;

        .icon {
          display: flex;
          width: 32rpx;
          height: 32rpx;
        }

        .text {
          height: 28rpx;
          font-family: Source Han Sans CN;
          font-size: 28rpx;
          font-weight: normal;
          font-stretch: normal;
          line-height: 28rpx;
          letter-spacing: 0rpx;
          color: #9ca3af;
        }
      }
    }

    .information {
      margin-left: 16rpx;
      padding: 26rpx 0 0 32rpx;
      border-left: dashed 2rpx #e1383c;

      .contain {
        margin-bottom: 16rpx;
        padding: 40rpx 0 40rpx 30rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        border: solid 2rpx rgba(229, 229, 229, 0.64);

        .title {
          font-family: Source Han Sans CN;
          font-size: 30rpx;
          font-weight: normal;
          font-stretch: normal;
          line-height: 46rpx;
          letter-spacing: 0rpx;
          color: #333333;
          display: flex;
          align-items: center;
          /* 垂直居中对齐 */
          justify-content: space-between;
          padding-right: 30rpx;
          /* 添加右侧内边距避免图片贴边 */
        }

        .title text {
          /* 新增：限制两行并省略 */
          display: -webkit-box;
          /* 弹性盒模型，用于配合 line-clamp */
          -webkit-box-orient: vertical;
          /* 垂直排列 */
          -webkit-line-clamp: 2;
          /* 限制最大行数为 2 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 显示省略号 */
        }

        .titleIcon {
          width: 12rpx;
          height: 21rpx;
          margin-left: 12rpx;
          /* 文本和图片之间添加间距 */
        }

        .time {
          display: flex;
          align-items: center;
          margin: 24rpx 0;

          .timeIcon {
            width: 26rpx;
            height: 26rpx;
            margin-right: 10rpx;
          }

          text {
            font-family: Source Han Sans CN;
            font-size: 26rpx;
            font-weight: normal;
            font-stretch: normal;
            letter-spacing: 0rpx;
            color: #9ca3af;
          }
        }

        .detail {
          padding-right: 30rpx;
          font-family: Source Han Sans CN;
          font-size: 28rpx;
          font-weight: normal;
          font-stretch: normal;
          line-height: 38rpx;
          letter-spacing: -1rpx;
          color: #4b5563;

          text {
            /* 新增：限制两行并省略 */
            display: -webkit-box;
            /* 弹性盒模型，用于配合 line-clamp */
            -webkit-box-orient: vertical;
            /* 垂直排列 */
            -webkit-line-clamp: 3;
            /* 限制最大行数为 2 */
            overflow: hidden;
            /* 超出部分隐藏 */
            text-overflow: ellipsis;
            /* 显示省略号 */
          }
        }
      }
    }
  }
</style>